<template>
  <section id="comments" class="comments-section section">
    <h2 class="section-title">游客评论 <span class="comment-count">({{ comments.length }}条)</span></h2>
    
    <div class="comments-container">
      <!-- 评论统计信息 -->
      <div class="comment-stats">
        <div class="stat-item">
          <div class="stat-value">{{ avgRating.toFixed(1) }}</div>
          <div class="stat-stars">
            <div class="star-rating large">
              <span v-for="n in 5" :key="n" :class="{ 'filled': n <= Math.round(avgRating) }">★</span>
            </div>
          </div>
          <div class="stat-label">平均评分</div>
        </div>
        <div class="rating-distribution">
          <div v-for="i in 5" :key="i" class="rating-bar">
            <div class="rating-label">{{ 6-i }}星</div>
            <div class="rating-progress">
              <div class="rating-progress-bar" 
                   :style="{width: `${getRatingPercentage(6-i)}%`}"></div>
            </div>
            <div class="rating-count">{{ getRatingCount(6-i) }}</div>
          </div>
        </div>
      </div>

      <!-- 发表评论 -->
      <div class="post-comment">
        <h3 class="comment-form-title">分享你的体验</h3>
        <div class="rating-select">
          <span class="rating-label">评分: </span>
          <div class="star-rating-select">
            <span v-for="n in 5" :key="n" 
                  :class="{ 'filled': n <= newCommentRating }" 
                  @click="newCommentRating = n">★</span>
          </div>
        </div>
        <textarea
            v-model="newComment"
            placeholder="写下你的评论..."
            class="comment-textarea"
            rows="3"
        ></textarea>
        <div class="comment-form-footer">
          <div class="character-count" :class="{'char-limit-warning': newComment.length > 450}">
            {{ newComment.length }}/500
          </div>
          <button
              @click="postComment"
              class="btn-post-comment"
              :disabled="!canPostComment"
          >
            <i class="icon-send"></i>发表评论
          </button>
        </div>
      </div>

      <!-- 评论筛选 -->
      <div class="comment-filters">
        <div class="filter-group">
          <span class="filter-label">筛选:</span>
          <button 
            class="filter-button" 
            :class="{'active': activeFilter === 'all'}"
            @click="setFilter('all')">全部</button>
          <button 
            class="filter-button" 
            :class="{'active': activeFilter === 'positive'}"
            @click="setFilter('positive')">好评 (4-5星)</button>
          <button 
            class="filter-button" 
            :class="{'active': activeFilter === 'negative'}"
            @click="setFilter('negative')">差评 (1-3星)</button>
        </div>
        <div class="filter-group">
          <span class="filter-label">排序:</span>
          <button 
            class="filter-button" 
            :class="{'active': sortOrder === 'newest'}"
            @click="setSorting('newest')">最新</button>
          <button 
            class="filter-button" 
            :class="{'active': sortOrder === 'helpful'}"
            @click="setSorting('helpful')">最有帮助</button>
        </div>
      </div>

      <!-- 评论列表 -->
      <div class="comments-list" v-if="paginatedComments.length > 0">
        <div
            v-for="(comment) in paginatedComments"
            :key="comment.id"
            class="comment-item"
            :class="{'featured': comment.featured}"
        >
          <!-- 评论内容 -->
          <div class="comment-header">
            <div class="comment-user">
              <img :src="comment.avatar" class="comment-avatar" :alt="comment.username" />
              <div class="comment-user-info">
                <div class="comment-username">{{ comment.username }}</div>
                <div class="comment-meta">
                  <span class="comment-date">{{ formatDate(comment.date) }}</span>
                  <span v-if="comment.visitType" class="visit-type">{{ comment.visitType }}</span>
                </div>
              </div>
            </div>
            <div class="comment-rating">
              <div class="star-rating">
                <span v-for="n in 5" :key="n" :class="{ 'filled': n <= comment.rating }">★</span>
              </div>
            </div>
          </div>
          
          <div class="comment-content">
            <div v-if="comment.featured" class="featured-badge">
              <i class="icon-star"></i> 精选点评
            </div>
            <h4 v-if="comment.title" class="comment-title">{{ comment.title }}</h4>
            <p>{{ comment.text }}</p>
            <div v-if="comment.images && comment.images.length > 0" class="comment-images">
              <div v-for="(image, imgIndex) in comment.images" :key="imgIndex" class="comment-image">
                <img :src="image" @click="viewImage(image)" alt="用户上传图片" />
              </div>
            </div>
            <div class="comment-actions">
              <button
                  @click="toggleLike(comment)"
                  class="btn-like"
                  :class="{'liked': comment.userLiked}"
              >
                <i class="icon-like"></i>
                <span>有帮助 ({{ comment.likes }})</span>
              </button>
              <button
                  @click="toggleReply(comment)"
                  class="btn-reply"
              >
                <i class="icon-reply"></i> 回复
              </button>
              <button class="btn-report">
                <i class="icon-flag"></i> 举报
              </button>
            </div>
          </div>

          <!-- 回复输入框 -->
          <div v-if="comment.showReply" class="reply-form">
            <textarea
                v-model="comment.replyText"
                placeholder="写下你的回复..."
                class="reply-textarea"
                rows="2"
            ></textarea>
            <div class="reply-form-footer">
              <button
                  @click="hideReply(comment)"
                  class="btn-cancel-reply"
              >
                取消
              </button>
              <button
                  @click="postReply(comment)"
                  class="btn-post-reply"
                  :disabled="!comment.replyText || comment.replyText.trim() === ''"
              >
                发表回复
              </button>
            </div>
          </div>

          <!-- 回复列表 -->
          <div v-if="comment.replies && comment.replies.length > 0" class="replies-list">
            <div class="replies-header">
              <span class="replies-count">{{ comment.replies.length }}条回复</span>
            </div>
            <div
                v-for="(reply) in comment.replies.slice(0, comment.showAllReplies ? comment.replies.length : 2)"
                :key="reply.id"
                class="reply-item"
                :class="{'official': reply.isOfficial}"
            >
              <div class="reply-header">
                <div class="reply-user">
                  <img :src="reply.avatar" class="reply-avatar" :alt="reply.username" />
                  <div class="reply-user-info">
                    <div class="reply-username">
                      {{ reply.username }}
                      <span v-if="reply.isOfficial" class="official-tag">官方回复</span>
                    </div>
                    <div class="reply-date">{{ formatDate(reply.date) }}</div>
                  </div>
                </div>
              </div>
              <div class="reply-content">
                <p>{{ reply.text }}</p>
                <div class="reply-actions">
                  <button
                      @click="toggleLike(reply)"
                      class="btn-like"
                      :class="{'liked': reply.userLiked}"
                  >
                    <i class="icon-like"></i>
                    <span>{{ reply.likes }}</span>
                  </button>
                </div>
              </div>
            </div>
            <button
                v-if="comment.replies.length > 2"
                @click="toggleShowAllReplies(comment)"
                class="btn-show-replies"
            >
              <i :class="comment.showAllReplies ? 'icon-chevron-up' : 'icon-chevron-down'"></i>
              {{ comment.showAllReplies ? '收起回复' : `查看全部${comment.replies.length}条回复` }}
            </button>
          </div>
        </div>
      </div>
      
      <!-- 无评论状态 -->
      <div v-else class="no-comments">
        <div class="no-comments-icon">📝</div>
        <p>暂无评论，来留下第一条评论吧！</p>
      </div>

      <!-- 分页 -->
      <div v-if="totalPages > 1" class="comments-pagination">
        <button
            @click="prevPage"
            :disabled="currentPage === 1"
            class="page-button"
        >
          <i class="icon-chevron-left"></i> 上一页
        </button>
        
        <div class="page-numbers">
          <button 
            v-if="currentPage > 3" 
            @click="currentPage = 1"
            class="page-number"
          >1</button>
          
          <span v-if="currentPage > 3">...</span>
          
          <button 
            v-for="page in visiblePageNumbers" 
            :key="page"
            @click="currentPage = page"
            class="page-number"
            :class="{'active': currentPage === page}"
          >{{ page }}</button>
          
          <span v-if="currentPage < totalPages - 2">...</span>
          
          <button 
            v-if="currentPage < totalPages - 2" 
            @click="currentPage = totalPages"
            class="page-number"
          >{{ totalPages }}</button>
        </div>
        
        <button
            @click="nextPage"
            :disabled="currentPage === totalPages"
            class="page-button"
        >
          下一页 <i class="icon-chevron-right"></i>
        </button>
      </div>
    </div>
  </section>
</template>

<script>
export default {
  name: 'CommentSection',
  props: {
    cityId: {
      type: [Number, String],
      default: null
    }
  },
  data() {
    return {
      newComment: '', // 新评论内容
      newCommentRating: 5, // 新评论的评分
      comments: [], // 所有评论
      currentPage: 1, // 当前页码
      commentsPerPage: 5, // 每页显示的评论数量
      isLoading: false,
      activeFilter: 'all', // 当前筛选 - all, positive, negative
      sortOrder: 'newest', // 排序方式 - newest, helpful
    };
  },
  computed: {
    // 计算可见的页码
    visiblePageNumbers() {
      const delta = 1; // 当前页前后显示的页码数
      let range = [];
      const totalPages = this.totalPages;
      const currentPage = this.currentPage;

      const startPage = Math.max(1, currentPage - delta);
      const endPage = Math.min(totalPages, currentPage + delta);

      for (let i = startPage; i <= endPage; i++) {
        range.push(i);
      }

      return range;
    },
    
    // 计算平均评分
    avgRating() {
      if (this.comments.length === 0) return 0;
      
      const sum = this.comments.reduce((acc, comment) => acc + (comment.rating || 0), 0);
      return sum / this.comments.length;
    },
    
    // 筛选后的评论
    filteredComments() {
      let result = [...this.comments];
      
      // 应用筛选
      if (this.activeFilter === 'positive') {
        result = result.filter(comment => comment.rating >= 4);
      } else if (this.activeFilter === 'negative') {
        result = result.filter(comment => comment.rating < 4);
      }
      
      // 应用排序
      if (this.sortOrder === 'newest') {
        result.sort((a, b) => new Date(b.date) - new Date(a.date));
      } else if (this.sortOrder === 'helpful') {
        result.sort((a, b) => b.likes - a.likes);
      }
      
      return result;
    },
    
    // 分页后的评论
    paginatedComments() {
      const start = (this.currentPage - 1) * this.commentsPerPage;
      const end = start + this.commentsPerPage;
      return this.filteredComments.slice(start, end);
    },
    
    // 总页数
    totalPages() {
      return Math.ceil(this.filteredComments.length / this.commentsPerPage) || 1;
    },
    
    // 验证是否可以发表评论
    canPostComment() {
      return this.newComment.trim() !== '' && 
             this.newComment.length <= 500 &&
             this.newCommentRating > 0;
    }
  },
  mounted() {
    console.log('CommentSection mounted, cityId:', this.cityId);
    
    // 如果有cityId，则加载该城市的评论
    if (this.cityId) {
      this.fetchComments();
    } else {
      // 没有cityId时，显示一些演示评论
      this.loadDemoComments();
    }
  },
  watch: {
    cityId(newVal) {
      if (newVal) {
        console.log('cityId changed, new value:', newVal);
        this.fetchComments();
      }
    }
  },
  methods: {
    // 加载评论数据
    async fetchComments() {
      this.isLoading = true;
      try {
        // 这里应该是从API获取评论的逻辑
        // const response = await getCommentsByCityId(this.cityId);
        // this.comments = response.data;
        
        console.log('Fetching comments for cityId:', this.cityId);
        
        // 暂时使用演示数据
        setTimeout(() => {
          this.loadDemoComments();
          this.isLoading = false;
          console.log('Demo comments loaded:', this.comments.length);
        }, 500);
      } catch (error) {
        console.error('获取评论失败:', error);
        this.isLoading = false;
      }
    },
    
    // 获取某个评分的数量
    getRatingCount(rating) {
      return this.comments.filter(comment => Math.round(comment.rating) === rating).length;
    },
    
    // 获取某个评分的百分比
    getRatingPercentage(rating) {
      if (this.comments.length === 0) return 0;
      return (this.getRatingCount(rating) / this.comments.length) * 100;
    },
    
    // 设置筛选条件
    setFilter(filter) {
      this.activeFilter = filter;
      this.currentPage = 1;
    },
    
    // 设置排序方式
    setSorting(sort) {
      this.sortOrder = sort;
      this.currentPage = 1;
    },
    
    // 查看图片
    viewImage(image) {
      // 这里可以实现查看大图的功能
      console.log('View image:', image);
    },
    
    // 隐藏回复框
    hideReply(comment) {
      comment.showReply = false;
      comment.replyText = '';
    },
    
    // 加载演示评论
    loadDemoComments() {
      this.comments = [
        {
          id: 1,
          username: '旅行爱好者',
          avatar: 'https://randomuser.me/api/portraits/women/44.jpg',
          rating: 5,
          title: '美不胜收的旅行体验',
          text: '这个城市真是太美了，特别是那些古老的建筑和街道，充满了历史感。强烈推荐大家来这里旅游！我们在这里度过了美好的五天，每天都有新的发现。当地人非常友好，而且餐厅的食物味道很棒。',
          date: new Date('2023-12-25'),
          likes: 42,
          userLiked: false,
          visitType: '家庭出游',
          featured: true,
          images: [
            'https://images.unsplash.com/photo-1501594907352-04cda38ebc29',
            'https://images.unsplash.com/photo-1522093537031-3ee69e6b1746'
          ],
          showReply: false,
          showAllReplies: false,
          replies: [
            {
              id: 101,
              username: '摄影师小王',
              avatar: 'https://randomuser.me/api/portraits/men/32.jpg',
              text: '完全同意！我上个月刚去过，拍了好多照片。春天去最美，花开满城，景色宜人。你有去过城南的那个历史博物馆吗？非常值得一去！',
              date: new Date('2023-12-26'),
              likes: 15,
              userLiked: false,
            },
            {
              id: 102,
              username: '背包客',
              avatar: 'https://randomuser.me/api/portraits/women/68.jpg',
              text: '请问有没有推荐的住宿地点？准备下个月去，想找一个位置好一点的酒店。',
              date: new Date('2023-12-28'),
              likes: 3,
              userLiked: false,
            },
            {
              id: 103,
              username: '旅行爱好者',
              avatar: 'https://randomuser.me/api/portraits/women/44.jpg',
              text: '@背包客 市中心有很多不错的青旅，性价比高，而且地理位置优越。我住的是城西的阳光酒店，离景点很近，交通也方便。',
              date: new Date('2023-12-29'),
              likes: 8,
              userLiked: false,
            }
          ]
        },
        {
          id: 2,
          username: '美食探索者',
          avatar: 'https://randomuser.me/api/portraits/men/86.jpg',
          rating: 4,
          title: '美食天堂，但价格偏高',
          text: '当地的美食真是令人难忘，尤其是那家老字号的面馆，味道真的太棒了！不过物价有点高，预算紧张的朋友需要做好准备。总体来说还是很推荐，特别是对美食感兴趣的朋友。',
          date: new Date('2023-12-20'),
          likes: 28,
          userLiked: false,
          visitType: '独自旅行',
          featured: false,
          images: ['https://images.unsplash.com/photo-1504674900247-0877df9cc836'],
          showReply: false,
          showAllReplies: false,
          replies: [
            {
              id: 201,
              username: '本地吃货',
              avatar: 'https://randomuser.me/api/portraits/women/24.jpg',
              text: '如果你喜欢那家面馆，也可以试试东区的那家小饭馆，价格更亲民，味道也很棒！',
              date: new Date('2023-12-21'),
              likes: 19,
              userLiked: false,
            },
            {
              id: 202,
              username: '城市管理员',
              avatar: 'https://randomuser.me/api/portraits/men/45.jpg',
              text: '感谢您的反馈！我们会考虑在旅游手册中增加更多不同价位的餐厅推荐，以满足不同游客的需求。',
              date: new Date('2023-12-22'),
              likes: 5,
              isOfficial: true,
              userLiked: false,
            }
          ]
        },
        {
          id: 3,
          username: '历史爱好者',
          avatar: 'https://randomuser.me/api/portraits/men/22.jpg',
          rating: 5,
          title: '历史底蕴深厚的城市',
          text: '这座城市的博物馆收藏非常丰富，展示了从古至今的历史变迁。参观需要预约，大家记得提前安排。我在这里呆了三天，感觉时间还不够用，很多地方都值得深入了解。',
          date: new Date('2023-12-15'),
          likes: 35,
          userLiked: false,
          visitType: '朋友结伴',
          featured: false,
          showReply: false,
          showAllReplies: false,
          replies: []
        },
        {
          id: 4,
          username: '自然探险家',
          avatar: 'https://randomuser.me/api/portraits/women/90.jpg',
          rating: 4.5,
          title: '城市周边的自然风光也很美',
          text: '除了城区的历史景点，我强烈推荐大家到郊外的山区走一走。那里空气清新，景色宜人，而且还能参加各种户外活动。我们租了自行车环湖骑行，是此行最美好的记忆之一。',
          date: new Date('2023-11-30'),
          likes: 27,
          userLiked: false,
          visitType: '情侣出游',
          featured: false,
          images: [
            'https://images.unsplash.com/photo-1501785888041-af3ef285b470',
            'https://images.unsplash.com/photo-1476514525535-07fb3b4ae5f1',
            'https://images.unsplash.com/photo-1469854523086-cc02fe5d8800'
          ],
          showReply: false,
          showAllReplies: false,
          replies: []
        },
        {
          id: 5,
          username: '预算旅行者',
          avatar: 'https://randomuser.me/api/portraits/men/55.jpg',
          rating: 3,
          title: '景色不错但消费偏高',
          text: '城市景色确实很美，但整体消费水平偏高，特别是在旅游旺季。住宿、餐饮和景点门票都不便宜。建议大家提前做好预算规划，并尝试使用一些折扣券或旅游套餐。',
          date: new Date('2023-11-15'),
          likes: 41,
          userLiked: false,
          visitType: '商务旅行',
          featured: false,
          showReply: false,
          showAllReplies: false,
          replies: [
            {
              id: 501,
              username: '城市旅游局',
              avatar: 'https://randomuser.me/api/portraits/men/75.jpg',
              text: '感谢您的宝贵意见！我们会继续优化旅游体验，同时增加更多不同价位的选择。欢迎您再次光临我们的城市，下次可以选择淡季来访，价格会相对亲民一些。',
              date: new Date('2023-11-16'),
              likes: 12,
              isOfficial: true,
              userLiked: false,
            }
          ]
        },
        {
          id: 6,
          username: '文化体验者',
          avatar: 'https://randomuser.me/api/portraits/women/33.jpg',
          rating: 5,
          title: '深入了解当地文化的好地方',
          text: '这次旅行最大的收获是参加了当地的文化体验活动，学习了传统工艺制作，还参加了民俗表演。这些活动让我对这座城市的文化有了更深入的理解，非常推荐给想要深度旅行的朋友们。',
          date: new Date('2023-10-25'),
          likes: 38,
          userLiked: false,
          visitType: '教育旅行',
          featured: true,
          images: ['https://images.unsplash.com/photo-1516307365426-bea591f05011'],
          showReply: false,
          showAllReplies: false,
          replies: []
        },
        {
          id: 7,
          username: '周末短途游',
          avatar: 'https://randomuser.me/api/portraits/men/41.jpg',
          rating: 4,
          title: '周末度假的理想选择',
          text: '作为周末短途游的目的地，这座城市非常合适。从邻近城市开车过来只需要2小时，景点相对集中，很容易安排行程。我们在这里度过了愉快的周末，感觉很充实但又不会太赶。',
          date: new Date('2023-10-10'),
          likes: 22,
          userLiked: false,
          visitType: '周末度假',
          featured: false,
          showReply: false,
          showAllReplies: false,
          replies: []
        },
        {
          id: 8,
          username: '妈妈游记',
          avatar: 'https://randomuser.me/api/portraits/women/63.jpg',
          rating: 4.5,
          title: '带孩子出游的好选择',
          text: '这座城市对家庭游非常友好，有许多适合儿童的博物馆和游乐设施。我们带着5岁和8岁的孩子一起来，他们玩得很开心，尤其喜欢科技馆和动物园。餐厅也普遍提供儿童餐和高椅。',
          date: new Date('2023-09-20'),
          likes: 32,
          userLiked: false,
          visitType: '家庭出游',
          featured: false,
          showReply: false,
          showAllReplies: false,
          replies: [
            {
              id: 801,
              username: '旅行达人',
              avatar: 'https://randomuser.me/api/portraits/women/28.jpg',
              text: '完全同意！我上个月也带孩子去了，城北的那个主题乐园特别适合小朋友，下次可以试试。',
              date: new Date('2023-09-22'),
              likes: 8,
              userLiked: false,
            }
          ]
        },
        {
          id: 9,
          username: '老年旅行者',
          avatar: 'https://randomuser.me/api/portraits/men/67.jpg',
          rating: 3.5,
          title: '适合慢节奏游览，但缺少无障碍设施',
          text: '这个城市有很多值得参观的地方，节奏也不会太快，适合我们这些老年人慢慢游览。但是有些景点的无障碍设施不够完善，坡道和电梯较少，对行动不便的游客不太友好。',
          date: new Date('2023-09-05'),
          likes: 29,
          userLiked: false,
          visitType: '银发族旅行',
          featured: false,
          showReply: false,
          showAllReplies: false,
          replies: [
            {
              id: 901,
              username: '城市管理员',
              avatar: 'https://randomuser.me/api/portraits/men/45.jpg',
              text: '感谢您的反馈！我们正在逐步改善各景点的无障碍设施，已将您的建议记录下来，会在下一阶段的改造中予以考虑。',
              date: new Date('2023-09-06'),
              likes: 15,
              isOfficial: true,
              userLiked: false,
            }
          ]
        },
        {
          id: 10,
          username: '摄影爱好者',
          avatar: 'https://randomuser.me/api/portraits/men/29.jpg',
          rating: 5,
          title: '摄影天堂，光线和景色绝佳',
          text: '作为一名摄影爱好者，我被这座城市的光线和景色深深吸引。无论是黄昏时分的古建筑，还是清晨的城市公园，都能拍出令人满意的照片。特别推荐河边的观景台，日落时分景色无与伦比。',
          date: new Date('2023-08-15'),
          likes: 45,
          userLiked: false,
          visitType: '摄影之旅',
          featured: false,
          images: [
            'https://images.unsplash.com/photo-1493246507139-91e8fad9978e',
            'https://images.unsplash.com/photo-1470093851219-69951fcbb533'
          ],
          showReply: false,
          showAllReplies: false,
          replies: []
        },
        {
          id: 11,
          username: '美食博主',
          avatar: 'https://randomuser.me/api/portraits/women/79.jpg',
          rating: 4.5,
          title: '舌尖上的城市之旅',
          text: '这座城市的美食值得专门为它来一次旅行！从街头小吃到米其林餐厅，从传统美食到创新料理，种类繁多且品质上乘。我尤其推荐城南的美食街，那里有许多当地特色小吃，价格也很亲民。',
          date: new Date('2023-08-03'),
          likes: 37,
          userLiked: false,
          visitType: '美食之旅',
          featured: false,
          images: ['https://images.unsplash.com/photo-1414235077428-338989a2e8c0'],
          showReply: false,
          showAllReplies: false,
          replies: []
        },
        {
          id: 12,
          username: '背包客小李',
          avatar: 'https://randomuser.me/api/portraits/men/81.jpg',
          rating: 2,
          title: '景色不错但服务有待提高',
          text: '虽然城市景色优美，但我在这次旅行中遇到了一些服务问题。部分景点的工作人员态度冷漠，公共交通也不够便捷。希望城市管理部门能够改进这些问题，提升整体旅游体验。',
          date: new Date('2023-07-22'),
          likes: 19,
          userLiked: false,
          visitType: '背包旅行',
          featured: false,
          showReply: false,
          showAllReplies: false,
          replies: [
            {
              id: 1201,
              username: '城市旅游局',
              avatar: 'https://randomuser.me/api/portraits/men/75.jpg',
              text: '非常抱歉您在旅行中遇到了不愉快的体验。我们正在加强对服务人员的培训，并优化公共交通线路。感谢您的宝贵意见，这对我们改进工作非常重要。',
              date: new Date('2023-07-23'),
              likes: 7,
              isOfficial: true,
              userLiked: false,
            },
            {
              id: 1202,
              username: '另一位游客',
              avatar: 'https://randomuser.me/api/portraits/women/42.jpg',
              text: '我上个月去的时候也有类似的感受，特别是在主要景点，服务质量确实有待提高。',
              date: new Date('2023-07-24'),
              likes: 3,
              userLiked: false,
            }
          ]
        }
      ];
    },
    
    // 发表评论
    postComment() {
      if (!this.canPostComment) return;
      
      // 实际应用中这里应该调用API将评论发送到服务器
      // const response = await postComment(this.cityId, this.newComment, this.newCommentRating);
      
      // 暂时模拟添加评论
      this.comments.unshift({
        id: Date.now(),
        username: '游客用户',
        avatar: 'https://randomuser.me/api/portraits/lego/1.jpg',
        rating: this.newCommentRating,
        text: this.newComment,
        date: new Date(),
        likes: 0,
        userLiked: false,
        visitType: '自由行',
        featured: false,
        showReply: false,
        showAllReplies: false,
        replies: [],
      });
      
      this.newComment = '';
      this.newCommentRating = 5;
      // 确保显示第一页，以便看到刚发布的评论
      this.currentPage = 1;
      this.activeFilter = 'all';
      this.sortOrder = 'newest';
    },
    
    // 点赞
    toggleLike(item) {
      // 实际应用中这里应该调用API记录点赞状态
      // const response = await toggleLike(item.id);
      
      if (item.userLiked) {
        item.likes -= 1;
      } else {
        item.likes += 1;
      }
      item.userLiked = !item.userLiked;
    },
    
    // 显示/隐藏回复输入框
    toggleReply(comment) {
      comment.showReply = !comment.showReply;
      comment.replyText = '';
    },
    
    // 发表回复
    postReply(comment) {
      if (!comment.replyText || comment.replyText.trim() === '') return;
      
      // 实际应用中这里应该调用API将回复发送到服务器
      // const response = await postReply(comment.id, comment.replyText);
      
      // 确保replies数组存在
      if (!comment.replies) {
        comment.replies = [];
      }
      
      // 添加回复
      comment.replies.push({
        id: Date.now(),
        username: '游客用户',
        avatar: 'https://randomuser.me/api/portraits/lego/2.jpg',
        text: comment.replyText,
        date: new Date(),
        likes: 0,
        userLiked: false,
      });
      
      // 清空并关闭回复框
      comment.showReply = false;
    },
    
    // 展开/折叠回复
    toggleShowAllReplies(comment) {
      comment.showAllReplies = !comment.showAllReplies;
    },
    
    // 上一页
    prevPage() {
      if (this.currentPage > 1) this.currentPage--;
    },
    
    // 下一页
    nextPage() {
      if (this.currentPage < this.totalPages) this.currentPage++;
    },
    
    // 日期格式化
    formatDate(date) {
      if (!date) return '';
      
      const d = new Date(date);
      const now = new Date();
      const diffTime = Math.abs(now - d);
      const diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24));
      
      // 如果是今天
      if (d.toDateString() === now.toDateString()) {
        return '今天';
      }
      
      // 如果是昨天
      const yesterday = new Date();
      yesterday.setDate(now.getDate() - 1);
      if (d.toDateString() === yesterday.toDateString()) {
        return '昨天';
      }
      
      // 如果是7天内
      if (diffDays <= 7) {
        return `${diffDays}天前`;
      }
      
      // 其他情况返回完整日期
      return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}-${String(d.getDate()).padStart(2, '0')}`;
    }
  },
};
</script>

<style scoped>
/* 评论区样式 */
.comments-section {
  background-color: #f9f9f9;
  margin-top: 40px;
  padding: 40px 20px;
  border-radius: 12px;
  box-shadow: 0 4px 12px rgba(0,0,0,0.05);
}

.section-title {
  font-size: 28px;
  margin-bottom: 40px;
  color: #333;
  text-align: center;
  font-weight: 700;
  position: relative;
}

.section-title::after {
  content: '';
  position: absolute;
  bottom: -10px;
  left: 50%;
  transform: translateX(-50%);
  width: 80px;
  height: 3px;
  background: linear-gradient(to right, #3498db, #2ecc71);
  border-radius: 3px;
}

.comment-count {
  font-size: 18px;
  color: #777;
  font-weight: normal;
  margin-left: 10px;
}

.comments-container {
  max-width: 1100px;
  margin: 0 auto;
}

/* 评论统计信息 */
.comment-stats {
  display: flex;
  justify-content: space-between;
  margin-bottom: 30px;
  background-color: white;
  padding: 25px;
  border-radius: 10px;
  box-shadow: 0 2px 8px rgba(0,0,0,0.08);
}

.stat-item {
  text-align: center;
}

.stat-value {
  font-size: 32px;
  font-weight: 700;
  color: #2c3e50;
}

.stat-stars {
  margin: 10px 0;
}

.star-rating.large {
  font-size: 24px;
}

.stat-label {
  font-size: 14px;
  color: #7f8c8d;
}

.rating-distribution {
  flex-grow: 1;
  display: flex;
  flex-direction: column;
  margin-left: 40px;
}

.rating-bar {
  display: flex;
  align-items: center;
  margin: 4px 0;
}

.rating-label {
  width: 40px;
  text-align: right;
  margin-right: 15px;
  font-size: 14px;
  color: #555;
}

.rating-progress {
  flex-grow: 1;
  background-color: #eee;
  height: 12px;
  border-radius: 6px;
  overflow: hidden;
  margin: 0 10px;
}

.rating-progress-bar {
  height: 100%;
  background: linear-gradient(to right, #3498db, #2ecc71);
}

.rating-count {
  width: 30px;
  font-size: 14px;
  color: #555;
}

/* 评论筛选 */
.comment-filters {
  display: flex;
  justify-content: space-between;
  margin: 30px 0;
  padding: 15px;
  background-color: white;
  border-radius: 8px;
  box-shadow: 0 2px 5px rgba(0,0,0,0.05);
  flex-wrap: wrap;
}

.filter-group {
  display: flex;
  align-items: center;
  margin: 5px 0;
}

.filter-label {
  color: #555;
  margin-right: 10px;
  font-size: 14px;
}

.filter-button {
  background: none;
  border: 1px solid #ddd;
  border-radius: 20px;
  padding: 8px 16px;
  margin: 0 5px;
  cursor: pointer;
  font-size: 14px;
  color: #555;
  transition: all 0.2s;
}

.filter-button:hover {
  background-color: #f0f0f0;
}

.filter-button.active {
  background-color: #3498db;
  border-color: #3498db;
  color: white;
}

/* 发表评论 */
.post-comment {
  margin-bottom: 30px;
  background-color: white;
  padding: 30px;
  border-radius: 10px;
  box-shadow: 0 2px 15px rgba(0,0,0,0.08);
}

.comment-form-title {
  font-size: 20px;
  margin-bottom: 20px;
  color: #2c3e50;
}

.rating-select {
  margin-bottom: 15px;
  display: flex;
  align-items: center;
}

.rating-label {
  margin-right: 10px;
  font-weight: 500;
}

.star-rating-select {
  font-size: 24px;
  color: #ddd;
  cursor: pointer;
}

.star-rating-select span {
  margin-right: 5px;
  transition: color 0.2s;
}

.star-rating-select span:hover,
.star-rating-select span.filled {
  color: #f1c40f;
}

.comment-textarea {
  width: 100%;
  padding: 15px;
  border: 1px solid #ddd;
  border-radius: 8px;
  resize: vertical;
  font-family: inherit;
  margin-bottom: 15px;
  font-size: 15px;
  transition: border-color 0.3s;
}

.comment-textarea:focus {
  border-color: #3498db;
  outline: none;
}

.comment-form-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.character-count {
  color: #777;
  font-size: 14px;
}

.char-limit-warning {
  color: #e74c3c;
}

.btn-post-comment {
  padding: 12px 24px;
  background-color: #3498db;
  color: white;
  border: none;
  border-radius: 6px;
  cursor: pointer;
  font-weight: 600;
  transition: background-color 0.3s;
  display: flex;
  align-items: center;
  gap: 8px;
}

.btn-post-comment:hover {
  background-color: #2980b9;
}

.btn-post-comment:disabled {
  background-color: #95a5a6;
  cursor: not-allowed;
}

/* 无评论状态 */
.no-comments {
  text-align: center;
  padding: 50px 0;
  background-color: white;
  border-radius: 10px;
  box-shadow: 0 2px 8px rgba(0,0,0,0.05);
}

.no-comments-icon {
  font-size: 60px;
  margin-bottom: 20px;
}

.no-comments p {
  color: #7f8c8d;
  font-size: 18px;
}

/* 评论列表 */
.comments-list {
  display: flex;
  flex-direction: column;
  gap: 25px;
}

.comment-item {
  padding: 25px;
  background-color: white;
  border-radius: 10px;
  box-shadow: 0 2px 8px rgba(0,0,0,0.08);
  transition: transform 0.2s, box-shadow 0.2s;
}

.comment-item:hover {
  transform: translateY(-3px);
  box-shadow: 0 5px 15px rgba(0,0,0,0.1);
}

.comment-item.featured {
  border-left: 4px solid #f1c40f;
}

.comment-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
}

.comment-user {
  display: flex;
  align-items: center;
}

.comment-avatar {
  width: 50px;
  height: 50px;
  border-radius: 50%;
  margin-right: 15px;
  object-fit: cover;
  border: 2px solid #fff;
  box-shadow: 0 2px 5px rgba(0,0,0,0.1);
}

.comment-username {
  font-weight: 700;
  color: #2c3e50;
  font-size: 16px;
  margin-bottom: 3px;
}

.comment-meta {
  display: flex;
  align-items: center;
  gap: 12px;
}

.comment-date {
  color: #7f8c8d;
  font-size: 13px;
}

.visit-type {
  font-size: 12px;
  background-color: #f8f9fa;
  color: #555;
  padding: 3px 8px;
  border-radius: 12px;
}

.comment-rating {
  display: flex;
  flex-direction: column;
  align-items: flex-end;
}

.star-rating {
  color: #ddd;
  font-size: 18px;
  letter-spacing: 2px;
}

.star-rating .filled {
  color: #f1c40f;
}

.featured-badge {
  display: inline-block;
  background-color: #fff8e1;
  color: #f1c40f;
  font-size: 12px;
  font-weight: 600;
  padding: 5px 10px;
  border-radius: 4px;
  margin-bottom: 10px;
  display: flex;
  align-items: center;
  gap: 6px;
  width: fit-content;
}

.comment-title {
  font-size: 18px;
  font-weight: 600;
  margin-bottom: 12px;
  color: #2c3e50;
}

.comment-content p {
  margin-bottom: 15px;
  line-height: 1.6;
  color: #333;
}

.comment-images {
  display: flex;
  gap: 10px;
  flex-wrap: wrap;
  margin: 15px 0;
}

.comment-image {
  width: 120px;
  height: 120px;
  border-radius: 8px;
  overflow: hidden;
  cursor: pointer;
}

.comment-image img {
  width: 100%;
  height: 100%;
  object-fit: cover;
  transition: transform 0.3s;
}

.comment-image img:hover {
  transform: scale(1.05);
}

.comment-actions {
  display: flex;
  gap: 20px;
  margin-top: 15px;
}

.btn-like, .btn-reply, .btn-report {
  display: flex;
  align-items: center;
  gap: 6px;
  background: none;
  border: none;
  color: #777;
  cursor: pointer;
  font-size: 14px;
  transition: color 0.2s;
}

.btn-like:hover, .btn-reply:hover {
  color: #3498db;
}

.btn-report:hover {
  color: #e74c3c;
}

.btn-like.liked {
  color: #3498db;
}

/* 回复输入框 */
.reply-form {
  margin-top: 20px;
  margin-left: 25px;
  padding: 20px;
  background-color: #f8f9fa;
  border-radius: 8px;
}

.reply-textarea {
  width: 100%;
  padding: 12px;
  border: 1px solid #ddd;
  border-radius: 6px;
  resize: vertical;
  font-family: inherit;
  margin-bottom: 15px;
  font-size: 14px;
}

.reply-form-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

.btn-cancel-reply {
  padding: 8px 15px;
  background-color: #f8f9fa;
  border: 1px solid #ddd;
  border-radius: 4px;
  color: #555;
  cursor: pointer;
}

.btn-post-reply {
  padding: 8px 15px;
  background-color: #3498db;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  transition: background-color 0.3s;
}

.btn-post-reply:hover {
  background-color: #2980b9;
}

.btn-post-reply:disabled {
  background-color: #95a5a6;
  cursor: not-allowed;
}

/* 回复列表 */
.replies-list {
  margin-top: 20px;
  margin-left: 25px;
  display: flex;
  flex-direction: column;
  gap: 15px;
}

.replies-header {
  padding: 0 0 8px 0;
  border-bottom: 1px solid #eee;
  margin-bottom: 5px;
}

.replies-count {
  color: #555;
  font-size: 14px;
  font-weight: 500;
}

.reply-item {
  padding: 15px;
  background-color: #f8f9fa;
  border-radius: 8px;
}

.reply-item.official {
  background-color: #ebf8ff;
  border-left: 3px solid #3498db;
}

.reply-header {
  display: flex;
  align-items: center;
  margin-bottom: 10px;
}

.reply-avatar {
  width: 35px;
  height: 35px;
  border-radius: 50%;
  margin-right: 10px;
  object-fit: cover;
}

.reply-username {
  font-weight: 600;
  color: #2c3e50;
  font-size: 14px;
}

.official-tag {
  background-color: #3498db;
  color: white;
  font-size: 11px;
  font-weight: 500;
  padding: 2px 6px;
  border-radius: 3px;
  margin-left: 8px;
}

.reply-date {
  font-size: 12px;
  color: #7f8c8d;
  margin-top: 2px;
}

.reply-content p {
  margin-bottom: 10px;
  font-size: 14px;
  line-height: 1.5;
  color: #333;
}

.reply-actions {
  display: flex;
  align-items: center;
  gap: 15px;
}

.btn-show-replies {
  background: none;
  border: none;
  color: #3498db;
  cursor: pointer;
  margin-top: 10px;
  align-self: flex-start;
  font-size: 14px;
  display: flex;
  align-items: center;
  gap: 6px;
}

/* 分页 */
.comments-pagination {
  margin-top: 40px;
  display: flex;
  justify-content: center;
  align-items: center;
  gap: 15px;
}

.page-button {
  padding: 10px 15px;
  background-color: white;
  border: 1px solid #ddd;
  border-radius: 6px;
  cursor: pointer;
  display: flex;
  align-items: center;
  gap: 5px;
  transition: all 0.2s;
}

.page-button:hover:not(:disabled) {
  background-color: #f8f9fa;
  border-color: #3498db;
  color: #3498db;
}

.page-button:disabled {
  opacity: 0.5;
  cursor: not-allowed;
}

.page-numbers {
  display: flex;
  gap: 8px;
  align-items: center;
}

.page-number {
  width: 35px;
  height: 35px;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 50%;
  border: 1px solid #ddd;
  background-color: white;
  cursor: pointer;
  transition: all 0.2s;
}

.page-number:hover:not(.active) {
  border-color: #3498db;
  color: #3498db;
}

.page-number.active {
  background-color: #3498db;
  color: white;
  border-color: #3498db;
}

@media (max-width: 768px) {
  .comment-stats {
    flex-direction: column;
    gap: 20px;
  }
  
  .rating-distribution {
    margin-left: 0;
    width: 100%;
  }
  
  .comment-filters {
    flex-direction: column;
    gap: 15px;
  }
  
  .filter-group {
    width: 100%;
    overflow-x: auto;
    padding-bottom: 5px;
  }
  
  .comment-user-info {
    max-width: 150px;
  }
  
  .comment-meta {
    flex-direction: column;
    align-items: flex-start;
    gap: 5px;
  }
  
  .comment-images {
    justify-content: center;
  }
}
</style>